<template>
  <view class="container">
    <!-- 页面标题 -->
    <view class="page-header">
      <view class="title">医疗教育视频平台</view>
      <view class="subtitle">专业医学知识分享，提升医疗技能</view>
    </view>

    <!-- 搜索框 -->
    <view class="search-box">
      <input type="text" placeholder="搜索视频、疾病或技能..." v-model="searchKeyword" @input="handleSearch" />
      <icon class="search-icon" type="search" size="20"></icon>
    </view>

    <!-- 分类标签 -->
    <scroll-view class="category-scroll" scroll-x :scroll-left="scrollLeft" scroll-with-animation>
      <view class="category-wrapper">
        <view class="category-item" :class="{ active: currentCategory === '全部' }" @click="currentCategory = '全部'">
          全部
        </view>
        <view class="category-item" :class="{ active: currentCategory === item }" @click="changeCurrentCategory(item)"
          v-for="(item, index) in uniqueCategories" :key="index">
          {{ item }}
        </view>
      </view>
    </scroll-view>

    <!-- 视频列表 -->
    <view class="video-list">
      <view class="video-card" v-for="(video, index) in filteredVideos" :key="index">
        <!-- 视频缩略图和播放按钮 -->
        <view class="video-thumbnail">
          <image :src="video.poster" mode="aspectFill" class="poster-image"></image>
          <view class="duration">{{ video.duration }}</view>
          <view class="play-btn" @click="playVideo(video, index)">
            <view class="triangle"></view>
          </view>
        </view>

        <!-- 视频信息 -->
        <view class="video-details">
          <view class="video-title">{{ video.title }}</view>
          <view class="video-meta">
            <view class="source">{{ video.source }}</view>
            <view class="category-tag">{{ video.category }}</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-if="filteredVideos.length === 0 && !isLoading">
      <image src="" mode="widthFix" class="empty-image"></image>
      <view class="empty-text">未找到相关视频</view>
      <button class="reset-btn" @click="resetFilters">重置筛选</button>
    </view>

    <!-- 加载中 -->
    <view class="loading-state" v-if="isLoading">
      <view class="spinner"></view>
      <view class="loading-text">加载中...</view>
    </view>

    <!-- 视频播放弹窗 -->
    <view class="video-modal" v-if="isVideoPlaying">
      <view class="modal-header">
        <view class="modal-title">{{ currentVideo.title }}</view>
        <view class="close-btn" @click="closeVideo">
          <icon type="clear" size="24" color="#ffffff"></icon>
        </view>
      </view>

      <view class="video-container">
        <video src="" controls autoplay preload="auto" class="video-player" @error="handleVideoError"
          @ended="closeVideo"></video>
      </view>

      <view class="video-description">
        <view class="description-title">视频简介</view>
        <view class="description-content">
          来源：{{ currentVideo.source }} | 分类：{{ currentVideo.category }}
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import api from '@/api/index'


export default {
  data() {
    return {
      // 视频数据（已替换为可直接播放的MP4地址+封面图）
      medicalVideos: [],

      // 状态管理
      currentCategory: "全部",
      searchKeyword: "",
      isLoading: false,
      isVideoPlaying: false,
      currentVideo: null,
      currentVideoUrl: "",
      instance: '',
      leftWidth: 0,
      scrollLeft: 0,
      categoryPositions: [], // 存储分类标签位置信息
      categoryWidths: [],
    };
  },

  computed: {
    // 获取唯一的分类列表
    uniqueCategories() {
      const categories = new Set();
      this.medicalVideos.forEach(video => {
        categories.add(video.category);
      });
      return Array.from(categories);
    },

    // 筛选视频
    filteredVideos() {
      return this.medicalVideos.filter(video => {
        // 分类筛选
        const categoryMatch = this.currentCategory === "全部" ||
          video.category === this.currentCategory;

        // 搜索筛选 - 添加安全检查
        const searchMatch = !this.searchKeyword ||
          (video.title && video.title.toLowerCase().includes(this.searchKeyword.toLowerCase())) ||
          (video.category && video.category.toLowerCase().includes(this.searchKeyword.toLowerCase())) ||
          (video.source && video.source.toLowerCase().includes(this.searchKeyword.toLowerCase()));
        return categoryMatch && searchMatch;
      });
    }
  },

  methods: {
    // 处理搜索（添加防抖优化）
    handleSearch() {
      clearTimeout(this.searchTimer);
      this.searchTimer = setTimeout(() => {
        console.log("搜索关键词：", this.searchKeyword);
      }, 300);
    },

    // 重置筛选条件
    resetFilters() {
      this.currentCategory = "全部";
      this.searchKeyword = "";
    },


    // 修改 playVideo 方法，跳转到 webView 页面
    playVideo(video, index) {
      // 使用 uni.navigateTo 跳转到 webView 页面，并传递 URL 参数
      uni.navigateTo({
        url: `/components/webView?url=${encodeURIComponent(video.url)}`
      });
    },

    // 移除 closeVideo 方法，因为不再需要关闭视频弹窗
    // handleVideoError 方法也可以移除，因为错误处理将在 webView 中进行

    changeCurrentCategory(category) {
      this.currentCategory = category;
      this.searchKeyword = ""; // 切换分类时清空搜索关键词

      // 找到当前分类的索引
      let index = this.uniqueCategories.indexOf(category);
      if (index === -1) index = 0; // 如果是"全部"分类，索引为0

      // 更新滚动位置
      this.scrollToCategory(index);
    },

    // 滚动到指定分类
    scrollToCategory(index) {
      // 确保位置信息已经获取到
      if (this.categoryPositions.length > 0 && this.categoryWidths.length > 0) {
        // 获取当前分类的位置和宽度
        const position = this.categoryPositions[index];
        const width = this.categoryWidths[index];
        if (position !== undefined && width !== undefined) {
          // 滚动到使当前项和下一项可见的位置
          // 简单起见，我们滚动到当前项的左侧位置加上一些偏移
          this.scrollLeft = position.left + width - 100;
        }
      }
    },
    async getvideosapi() {
      try {
        // 正确的调用方式
        const res = await api.getVideosApi()
        // 或者如果你用了命名导入：const res = await getUserApi()
        console.log('res', res);
        this.medicalVideos = res.data
      } catch (error) {
        console.error('获取菜单列表失败:', error);
      }
    },

  },


  onLoad() {
    // 页面加载初始化
    this.isLoading = true;
    // 模拟数据加载延迟
    setTimeout(() => {
      this.isLoading = false;
    }, 800);
    this.getvideosapi();
  },

  onUnload() {
    // 页面卸载时清除定时器
    clearTimeout(this.searchTimer);
  },
  mounted() {
    setTimeout(() => {
      const query = uni.createSelectorQuery().in(this);
      query
        .selectAll(".category-item")
        .boundingClientRect((data) => {
          if (data && data.length > 0) {
            // 保存所有分类项的位置和宽度信息
            this.categoryPositions = data.map(item => ({
              left: item.left,
              top: item.top
            }));

            this.categoryWidths = data.map(item => item.width);
          }
        })
        .exec();
    }, 1000);
  }
};
</script>

<style scoped>
.container {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f7;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

/* 页面头部 */
.page-header {
  padding: 30rpx 20rpx;
  background: linear-gradient(135deg, #165DFF, #0E42D2);
  color: #ffffff;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.subtitle {
  font-size: 24rpx;
  opacity: 0.9;
}

/* 搜索框 */
.search-box {
  position: relative;
  margin: 20rpx;
  background-color: #ffffff;
  border-radius: 8rpx;
  padding: 12rpx 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.search-box input {
  width: 100%;
  font-size: 28rpx;
  padding-right: 60rpx;
  height: 50rpx;
  line-height: 50rpx;
}

.search-icon {
  position: absolute;
  right: 20rpx;
  top: 50%;
  transform: translateY(-50%);
  color: #888888;
}

/* 分类标签 */
.category-scroll {
  width: 100%;
  white-space: nowrap;
  padding: 10rpx 0;
  background-color: #ffffff;
  border-bottom: 1px solid #eeeeee;
}

.category-wrapper {
  display: inline-flex;
  padding: 0 20rpx;
}

.category-item {
  padding: 12rpx 24rpx;
  margin-right: 16rpx;
  background-color: #f5f5f5;
  border-radius: 30rpx;
  font-size: 26rpx;
  color: #333333;
  transition: all 0.2s;
}

.category-item.active {
  background-color: #165DFF;
  color: #ffffff;
}

.category-item:last-child {
  margin-right: 0;
}

/* 视频列表 */
.video-list {
  padding: 20rpx;
  display: grid;
  grid-template-columns: 1fr;
  gap: 20rpx;
}

.video-card {
  background-color: #ffffff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  transition: transform 0.2s;
}

.video-card:hover {
  transform: translateY(-4rpx);
}

.video-thumbnail {
  position: relative;
  width: 100%;
  height: 400rpx;
}

.poster-image {
  width: 100%;
  height: 100%;
}

.duration {
  position: absolute;
  right: 10rpx;
  bottom: 10rpx;
  background-color: rgba(0, 0, 0, 0.6);
  color: #ffffff;
  font-size: 22rpx;
  padding: 2rpx 8rpx;
  border-radius: 4rpx;
}

/* 播放按钮样式 */
.play-btn {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 80rpx;
  height: 80rpx;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

.triangle {
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 20rpx 0 20rpx 35rpx;
  border-color: transparent transparent transparent #ffffff;
  margin-left: 5rpx;
}

.play-btn:hover {
  background-color: rgba(255, 68, 0, 0.8);
  transform: translate(-50%, -50%) scale(1.1);
}

.video-details {
  padding: 15rpx;
}

.video-title {
  font-size: 26rpx;
  color: #333333;
  margin-bottom: 8rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  height: 62rpx;
}

.video-meta {
  display: flex;
  justify-content: space-between;
  font-size: 22rpx;
  color: #888888;
}

.source {
  max-width: 180rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.category-tag {
  background-color: #f0f5ff;
  color: #165DFF;
  padding: 2rpx 10rpx;
  border-radius: 4rpx;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 20rpx;
}

.empty-image {
  width: 200rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #888888;
  margin-bottom: 30rpx;
}

.reset-btn {
  background-color: #165DFF;
  color: #ffffff;
  padding: 12rpx 40rpx;
  border-radius: 30rpx;
  font-size: 26rpx;
  border: none;
}

/* 加载状态 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 20rpx;
}

.spinner {
  width: 50rpx;
  height: 50rpx;
  border: 5rpx solid #eeeeee;
  border-top: 5rpx solid #165DFF;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #888888;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

/* 视频播放弹窗 */
.video-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #000000;
  z-index: 9999;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background-color: #1a1a1a;
  color: #ffffff;
}

.modal-title {
  font-size: 30rpx;
  font-weight: 500;
  flex: 1;
  margin-right: 50rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.close-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.video-container {
  width: 100%;
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx 0;
}

.video-player {
  width: 100%;
  height: auto;
  max-height: 70vh;
}

.video-description {
  background-color: #1a1a1a;
  color: #ffffff;
  padding: 20rpx;
}

.description-title {
  font-size: 28rpx;
  margin-bottom: 10rpx;
  font-weight: 500;
}

.description-content {
  font-size: 24rpx;
  opacity: 0.9;
}
</style>